package wang.lcs.pay.util.print;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

public class LogHttpResult extends PrintingHttpResult {

    private static final Logger LOG = LoggerFactory.getLogger(LogHttpResult.class);

    public LogHttpResult(Logger log) {
        super(new Print(log));
    }

    public LogHttpResult() {
        super(new Print(LOG));
    }

    private static class Print implements ResultValuePrinter {

        private Logger log;

        public Print(Logger log) {
            this.log = log;
        }

        private final List<String> lines = new ArrayList<String>();

        @Override
        public void printHeading(String heading) {
            this.lines.add("");
            this.lines.add(String.format("%s:", heading));
        }

        @Override
        public void printValue(String label, Object value) {
            if (value != null && value.getClass().isArray()) {
                value = CollectionUtils.arrayToList(value);
            }
            this.lines.add(String.format("%17s = %s", label, value));
        }

        @Override
        public void close() throws IOException {
            log.info("Log info for http request ! {}\n", this.lines.stream().collect(Collectors.joining("\n")));
            lines.clear();
        }
    }
}
